package com.zzc.interview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.zzc.interview.common.ErrorCode;
import com.zzc.interview.constant.CommonConstant;
import com.zzc.interview.exception.BusinessException;
import com.zzc.interview.exception.ThrowUtils;
import com.zzc.interview.mapper.OjQuestionMapper;
import com.zzc.interview.model.dto.ojQuestion.OjQuestionQueryRequest;
import com.zzc.interview.model.entity.OjQuestion;
import com.zzc.interview.model.entity.User;
import com.zzc.interview.model.vo.OjQuestionVO;
import com.zzc.interview.model.vo.UserVO;
import com.zzc.interview.service.OjQuestionService;
import com.zzc.interview.service.UserService;
import com.zzc.interview.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class OjQuestionServiceImpl extends ServiceImpl<OjQuestionMapper, OjQuestion> implements OjQuestionService {
    private final static Gson GSON = new Gson();

    @Resource
    private UserService userService;

    /**
     * 检测题目是否合法
     *
     * @param question
     * @param add
     */
    @Override
    public void validOjQuestion(OjQuestion question, boolean add) {
        if (question == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String title = question.getTitle();
        String content = question.getContent();
        String tags = question.getTags();
        String answer = question.getAnswer();
        String judgeCase = question.getJudgeCase();
        String judgeConfig = question.getJudgeConfig();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "题目内容过长");
        }
        if (StringUtils.isNotBlank(tags) && tags.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签内容过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "答案内容过长");
        }
        if (StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题用例内容过长");
        }
        if (StringUtils.isNotBlank(judgeConfig) && judgeConfig.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题配置内容过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<OjQuestion> getQueryWrapper(OjQuestionQueryRequest questionQueryRequest) {
        QueryWrapper<OjQuestion> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }

        Long id = questionQueryRequest.getId();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        List<String> tags = questionQueryRequest.getTags();
        String answer = questionQueryRequest.getAnswer();
        Long userId = questionQueryRequest.getUserId();

        String sortField = questionQueryRequest.getSortField(); // 这里是按照什么排序的
        String sortOrder = questionQueryRequest.getSortOrder();

        // 拼接查询条件，根据题目title、内容content、答案answer、标签tags进行模糊匹配
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        if (CollectionUtils.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    /**
     * 为查询到的单个题目信息，并绑定用户信息。
     * TODO 不知道有什么用
     *
     * @param question
     * @param loginUser
     * @return
     */
    @Override
    public OjQuestionVO getOjQuestionVO(OjQuestion question, User loginUser) {
        OjQuestionVO questionVO = OjQuestionVO.objToVo(question);
        UserVO userVO = userService.getUserVO(loginUser);
        questionVO.setUserVO(userVO);
        return questionVO;
    }

    /**
     * 为查询到的多个问题信息，绑定用户信息。
     *
     * @param questionPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<OjQuestionVO> getOjQuestionVOPage(Page<OjQuestion> questionPage, User loginUser) {
        List<OjQuestion> questionList = questionPage.getRecords();
        Page<OjQuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollectionUtils.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 1. 关联查询用户信息
//        Set<Long> userIdSet = questionList.stream().map(OjQuestion::getUserId).collect(Collectors.toSet());
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<OjQuestionVO> questionVOList = questionList.stream().map(question -> {
            OjQuestionVO questionVO = OjQuestionVO.objToVo(question);
            questionVO.setUserVO(userService.getUserVO(loginUser));
            return questionVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    @Override
    public Page<OjQuestion> getOjQuestionPage(Page<OjQuestion> questionPage, User loginUser) {
//        List<OjQuestion> questionList = questionPage.getRecords();
//        Page<OjQuestionUserVo> questionUserVoPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
//        if (CollectionUtils.isEmpty(questionList)) {
//            return questionUserVoPage;
//        }
//        // 填充用户信息
//        List<OjQuestionUserVo> collect = questionList.stream().map(question -> {
//            OjQuestionUserVo questionUserVo = OjQuestionUserVo.objToVo(question);
//            questionUserVo.setUserVO(userService.getUserVO(loginUser));
//            return questionUserVo;
//        }).collect(Collectors.toList());
//        questionUserVoPage.setRecords(collect);
        return questionPage;
    }
}




